package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.User;
import com.example.entity.UserVO;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.util.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    /**
     * 登录
     */
    @Override
    public UserVO login(User user){
        User userNew = userMapper.selectByUserid(user.getId());
        if(userNew == null ){
            //没有用户
            throw new CustomException("账号或密码错误");
        }
        //比较密码
        if(!user.getPassword().equals(userNew.getPassword())){
            throw new CustomException("账号或密码错误");
        }
        else {
            UserVO userVO = new UserVO();
            //生成token
            String token = JwtUtil.createToken(userNew.getName(), userNew.getRole(), userNew.getPassword());
            BeanUtils.copyProperties(userNew, userVO);
            userVO.setToken(token);
            return userVO;
        }
        //登录成功

    }
    /**注册
     *注册账号-cyp
     */
    @Override
    public void register(User user) {

//        student.setUsername(account.getUsername());
//        student.setPassword(account.getPassword());
//        this.add(student);
        userMapper.insert(user);
    }



    /**新增
     *
     */
    @Override
    public void add(User user) {
        User dbStudent = userMapper.selectByUserid(user.getId());
        if(dbStudent !=null)
        {
            //已有账号 不允许注册
            throw  new CustomException("账号已存在");

        }
        if(ObjectUtil.isEmpty(user.getName())){
            user.setName(user.getName());
        }
        //user.setRole(RoleEnum.STUDENT.name());
        userMapper.insert(user);
    }
    /**更新
     *-cyp
     */
    @Override
    public void updateById(User user) {
        userMapper.updateInfoByid(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public PageInfo<User> selectPage(Integer pageNum, Integer pageSize, User user) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList= userMapper.selectAll(user);
        return PageInfo.of(userList);
    }

}
